// pages/student/notice/notice.js
Page({
  data: {
    noticeList: [],
    isLoading: true,
    activeTab: 'all',
    page: 1,
    limit: 10,
    hasMore: true,
    errorMsg: ''
  },

  onLoad: function() {
    this.loadNotices(true);
  },

  onShow: function() {
    // 每次页面显示时刷新通知列表
    this.loadNotices(true);
  },

  onPullDownRefresh: function() {
    this.loadNotices(true).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadNotices(false);
    }
  },

  // 切换标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ 
      activeTab: tab,
      page: 1,
      noticeList: [],
      hasMore: true
    });
    this.loadNotices(true);
  },

  // 加载通知列表
  loadNotices: function(refresh = false) {
    if (this.data.isLoading && !refresh) return Promise.resolve();
    
    this.setData({ 
      isLoading: true,
      errorMsg: '',
      page: refresh ? 1 : this.data.page
    });
    
    // 如果是刷新，清空列表
    if (refresh) {
      this.setData({
        noticeList: [],
        hasMore: true
      });
    }
    
    return new Promise((resolve) => {
      wx.request({
        url: 'http://localhost:3000/api/notices',
        method: 'GET',
        data: {
          page: this.data.page,
          limit: this.data.limit
        },
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.statusCode === 200) {
            // 从响应中提取notices数组
            let newNotices = [];
            
            if (res.data && res.data.notices && Array.isArray(res.data.notices)) {
              newNotices = res.data.notices;
            } else if (Array.isArray(res.data)) {
              newNotices = res.data;
            } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
              newNotices = res.data.data;
            }
            
            // 获取本地已读通知ID列表
            const readNoticeIds = wx.getStorageSync('readNoticeIds') || [];
            
            // 标记已读状态
            newNotices = newNotices.map(notice => ({
              ...notice,
              isRead: readNoticeIds.includes(notice.id)
            }));
            
            // 根据当前标签筛选通知
            if (this.data.activeTab === 'read') {
              newNotices = newNotices.filter(notice => notice.isRead);
            } else if (this.data.activeTab === 'unread') {
              newNotices = newNotices.filter(notice => !notice.isRead);
            }
            
            const hasMore = newNotices.length === this.data.limit;
            
            // 安全地合并数组
            const currentList = refresh ? [] : this.data.noticeList;
            
            this.setData({
              noticeList: currentList.concat(newNotices),
              isLoading: false,
              hasMore: hasMore,
              page: this.data.page + 1
            });
          } else {
            this.setData({ 
              isLoading: false,
              errorMsg: res.data.message || '获取通知失败'
            });
            wx.showToast({
              title: '获取通知失败',
              icon: 'none'
            });
          }
          resolve();
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.setData({
            isLoading: false,
            hasMore: false,
            errorMsg: '网络连接失败，请检查网络'
          });
          resolve();
        }
      });
    });
  },

  // 查看通知详情
  viewNoticeDetail: function(e) {
    const noticeId = e.currentTarget.dataset.id;
    
    // 标记为已读
    this.markAsRead(noticeId);
    
    // 跳转到详情页
    wx.navigateTo({
      url: `/pages/student/notice/detail/detail?id=${noticeId}`
    });
  },

  // 标记通知为已读
  markAsRead: function(noticeId) {
    const noticeList = this.data.noticeList;
    const index = noticeList.findIndex(item => item.id === noticeId);
    
    if (index !== -1 && !noticeList[index].isRead) {
      // 先在本地标记为已读，提升用户体验
      const updatedList = [...noticeList];
      updatedList[index].isRead = true;
      
      this.setData({
        noticeList: updatedList
      });
      
      // 将已读状态保存到本地缓存
      const readNoticeIds = wx.getStorageSync('readNoticeIds') || [];
      if (!readNoticeIds.includes(noticeId)) {
        readNoticeIds.push(noticeId);
        wx.setStorageSync('readNoticeIds', readNoticeIds);
      }
    }
  },

  // 重试加载
  retryLoad: function() {
    this.loadNotices(true);
  }
});